// redirect 相关业务方法
import { platformTruth } from '@common/environment';
import { wechatUrl, alipayUrl, gAuthUrl } from '@constants/third';
import logger from '@common/logger';

const wechatRedirectUrl = (appId, url, comId) => {
    logger.info('跳转的链接为：', url);
    const redirect_uri = encodeURIComponent(url);
    if (comId) {
        window.location.href = `${wechatUrl.auth}?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&component_appid=${comId}#wechat_redirect`;
    } else {
        window.location.href = `${wechatUrl.auth}?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo#wechat_redirect`;
    }
};

const alipayRedirectUrl = (appid, url) => {
    const redirect_uri = encodeURIComponent(url);
    window.location.href = `${alipayUrl.auth}?app_id=${appid}&scope=auth_user&redirect_uri=${redirect_uri}&state=init`;
};

/**
 * 根据环境进行跳转
 * @param {String} appId appid
 * @param {String} url 跳转地址
 * @param {String} comId 微信托管平台component_id
 */
export const goToRedirect = (appId, url, comId) => {
    const { isWechat, isWechatMini, isAlipay } = platformTruth();
    if (isWechat || isWechatMini) {
        wechatRedirectUrl(appId, url, comId);
    } else if (isAlipay) {
        alipayRedirectUrl(comId, url);
    }
};

/**
 * 处理url为可用的url，剔除为此你返回的code
 * @param {String} url 需要处理的url
 */
export const dealUrlParam = (url) => {
    logger.info('需要处理的URL为：', url);
    const arr = `${url}`.split('?');
    const params = arr.length > 1 ? arr[1].split('&') : [];
    let query = '';
    for (let i = 0; i < params.length; i++) {
        const key = params[i].split('=')[0];
        if (key === 'code') {
            continue;
        }
        if (key === 'token') {
            continue;
        }
        query += params[i] + '&';
    }
    return `${arr[0]}?${query}`;
};

/**
 * 进行gAuth授权跳转，获取当堂gopen_id
 * @param {String} uri 回调url
 */
export const gAuthRedirect = (uri) => {
    const redirect_uri = encodeURIComponent(uri);
    logger.info('跳转链接', `${gAuthUrl.auth}?redirect_url=${redirect_uri}`);
    window.location.href = `${gAuthUrl.auth}?redirect_url=${redirect_uri}&timestamp=${new Date().getTime()}`; // 测试地址
};
